//获取数据库引用
const db = wx.cloud.database()

/**
 * 添加数据库
 * @param   collection   集合名称   String
 *          data         添加的数据    Object
*/
function add({ collection = "", data = {} }) {
    return db.collection(collection).add({
        data: data
    })
}



/**
 * 根据id查询记录
 * @params    collection  集合名称  String
 *             id           记录的id    string
*/

function getById({ collection = "", id = "" }) {
    return db.collection(collection).doc(id).get()
}

/**
 * 
 * 查询数据库
 * @params   collection  集合名称  String
 *           where        查询条件   Object
 * 
*/

function get({ collection = "", where = {}, field = {}, skip = 0, limit = 10, orderBy = { field: "addtime", sort: "desc" } }) {
    return db.collection(collection).where(where).skip(skip).limit(limit)
        .orderBy(orderBy.field, orderBy.sort)
        .field(field)
        .get()
}

/**
 * 
 * 执行累加
 * @params  collection 集合名称
 *          id       
 *          field      字段名称  String
 *          count       累加数量   Number
*/


function count({ collection = "", openid = "", menuid = "" }) {
    return db.collection(collection).where({ _openid: openid, menuid: menuid }).count()
}


/**
 * 累加
 * 
*/
function inc({ collection = "", id = "", field = "", count = 1 }) {
    return db.collection(collection).doc(id).update({
        data: {
            [field]: db.command.inc(count)
        }
    })

}

/**
 * 删除
 * 
*/
function remove({ collection = "", where = {} }) {
    return db.collection(collection).where(where).remove()
}





/**
 * 范围内查询
*/

function getIn({ collection = "", range = [], field = "" }) {
    return db.collection(collection).where({ [field]: db.command.in(range) }).get()
}

/**
 * 修改某一条记录
 * 
*/

function updateById({ collection = "", id = "", field = "", value = "" }) {
    return db.collection(collection).doc(id).update({
        data: {
            [field]: value
        }
    })
}


/**
 * 模糊查询
 * 
*/
function search({ collection = "", field = "", keyword = "" }) {
    return db.collection(collection).where({
        [field]: db.RegExp({
            regexp: keyword,
            options: 'i'
        })
    }).get()
}
export { add, get, getById, inc, count, remove, getIn, updateById, search }